const superagent = require('superagent') // 一个node环境http(s)请求中间件
const chalk = require('chalk');
const {
    wConfig
} = require('../../config.js');
const {
    Mysql
} = require('./config');
const {
    wechatAPIS
} = require('../../tools/wechatApi')
module.exports = async ctx => {
    let {
        code
    } = ctx.query;
    let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wConfig.appID}&secret=${wConfig.appsecret}&code=${code}&grant_type=authorization_code`
    let res1 = await superagent.get(url);
    let result = JSON.parse(res1.text);
    let oldUser = await isOldUser(result.openid);
    if (oldUser) {
        let subscribe = await wechatAPIS.getBaseInfo(result.openid);
        ctx.state.data = {
            code: '001',
            data: {
                oldUser: 1,
                ...subscribe,
                ...oldUser
            }
        }
        return;
    } else {
        try {
            let userInfo = await wechatAPIS.getUserInfo(result.openid, result.access_token);
            let subscribe = await wechatAPIS.getBaseInfo(result.openid);
            ctx.state.data = {
                code: '001',
                data: {
                    ...subscribe,
                    ...userInfo
                }
            }
        } catch (error) {
            throw error
        }

    }
};
async function isOldUser(openid) {
    return new Promise(async (resolve, reject) => {
        let sql = `SELECT user_info FROM userInfo WHERE open_id='${openid}'`;
        try {
            let res = await Mysql(sql);
            if (res.length) {
                resolve({
                    ...JSON.parse(res[0].user_info)
                });
                return res;
            } else {
                resolve(false)
                return false
            }
        } catch (error) {
            resolve(false)
            return false
        }
    })
}
